package com.xc.common.filter;

import com.xc.utils.PropertiesUtil;
import com.xc.utils.redis.CookieUtils;
import com.xc.utils.redis.RedisConst;
import com.xc.utils.redis.RedisShardedPoolUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

/**
 *  重置  user session有效期过滤器
 *  在 web.xml中新增filter节点
 *  Created by xiongcan on 2018/1/22.
 */
@Slf4j
public class SessionExpireFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {}


    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest httpServletRequest = (HttpServletRequest)servletRequest;


        String userLoginToken = CookieUtils.readLoginToken(httpServletRequest
                , PropertiesUtil.getProperty("user.cookie.name"));
        if(StringUtils.isNotEmpty(userLoginToken)){
            log.info("用户 token不为空，刷新有效期");
            String userjsonstr = RedisShardedPoolUtils.get(userLoginToken);
            if(StringUtils.isNotEmpty(userjsonstr)){
                RedisShardedPoolUtils.expire(userLoginToken
                        , RedisConst.RedisCacheExTime.REDIS_SESSION_EXTIME);
            }
        }

        String agentLoginToken = CookieUtils.readLoginToken(httpServletRequest
                , PropertiesUtil.getProperty("agent.cookie.name"));
        if(StringUtils.isNotEmpty(agentLoginToken)){
            log.info("代理 token不为空，刷新有效期");
            String agentJsonStr = RedisShardedPoolUtils.get(agentLoginToken);
            if(StringUtils.isNotEmpty(agentJsonStr)){
                RedisShardedPoolUtils.expire(agentLoginToken
                        , RedisConst.RedisCacheExTime.REDIS_SESSION_EXTIME);
            }
        }

        String adminLoginToken = CookieUtils.readLoginToken(httpServletRequest
                , PropertiesUtil.getProperty("admin.cookie.name"));
        if(StringUtils.isNotEmpty(adminLoginToken)){
            log.info("管理员 token不为空，刷新有效期");
            String adminJsonStr = RedisShardedPoolUtils.get(adminLoginToken);
            if(StringUtils.isNotEmpty(adminJsonStr)){
                RedisShardedPoolUtils.expire(adminLoginToken
                        , RedisConst.RedisCacheExTime.REDIS_SESSION_EXTIME);
            }
        }



        filterChain.doFilter(servletRequest,servletResponse);
    }

    @Override
    public void destroy() {
    }


}